/**
 * MarketDepth 市场买卖-深度数据
 * @Funtion 订阅
 * **/

import { ref } from "vue";
import * as pako from "pako";
import throttle from "lodash/throttle";
import { uuid } from "@util/utils";

export default function KlineGet() {
  const subDepthSocket = ref(null); // 订阅 市场买卖-深度数据
  const KlineWSUrl = "wss://api.btcgateway.pro/linear-swap-ws"; // K线数据 ws 地址

  const ThrottleGetDepth = throttle(function (data) {
    console.log("test", data);
  }, 300);

  /**
   * @classdesc  订阅 Web Socket 获取实时K线
   * @params params.params 订阅参数
   * @params params.recvCallback 回调函数
   **/
  const SubRequestWsDepth = async (params, recvCallback) => {
    var Params = MarketDepthGenerateRequsetParams(params);
    var message = JSON.stringify(Params);
    subDepthSocket.value = new WebSocket(KlineWSUrl); // 创建连接
    subDepthSocket.value.binaryType = "arraybuffer"; // 设置返回类型
    subDepthSocket.value.onopen = () => {
      subDepthSocket.value.send(message);
    };

    subDepthSocket.value.onmessage = (event) => {
      var _text = pako.inflate(event.data, {
        to: "string",
      });
      var recvData = JSON.parse(_text);
      // 心跳检测
      if (recvData.ping) {
        subDepthSocket.value.send(
          JSON.stringify({
            pong: recvData.ping,
          })
        );
      } else {
        if (!recvData.id) {
          recvCallback(recvData.tick);
          ThrottleGetDepth(recvData.tick);
          // _.throttle(recvCallback, 10);
        }
      }
    };

    subDepthSocket.value.onerror = () => {
      console.log("subDepthSocket.onerror");
      subDepthSocket.value.close();
    };
    subDepthSocket.value.onclose = () => {
      console.log("== subDepthSocket 市场买卖-深度数据 已暂停==");
    };
  };

  return {
    SubRequestWsDepth,
    ThrottleGetDepth,
  };
}

/**
 * @classdesc  MarketDepth 市场买卖-深度数据
 * @params params.symbol 数字货币
 * @params params.type   深度: 小数点后的价格
 **/
const MarketDepthGenerateRequsetParams = (params) => {
  const UUID = uuid();

  // 默认 20 档，暂不支持150挡
  var MAP_DEPTH = new Map([
    ["0.0000001", "step18"],
    ["0.000001", "step19"],
    ["0.00001", "step7"],
    ["0.0001", "step8"],
    ["0.001", "step9"],
    ["0.01", "step10"],
    ["0.1", "step11"],
    ["1", "step12"],
    ["10", "step13"],
  ]);

  var symbol = params.symbol;
  var type = "";
  if (!params.depth) type = "step11";
  else type = MAP_DEPTH.get(params.depth);
  return {
    sub: `market.${symbol}.depth.${type}`,
    id: UUID,
  };
};
